const express = require('express')
const cors = require('cors')
const Session = require('./routes/session.js')
const comment = require('./routes/comment.js')
const sort = require('./routes/sort.js')
const blog = require('./routes/blog.js')
const banner = require('./routes/banner.js')
const img = require('./routes/img.js')
const user_handle = require('./routes/user_handle.js')
var path=require("path")
const jwt = require('jsonwebtoken')
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/Blog')

const http = require('http');
const https = require('https');
var fs = require('fs');


const options = {
     key:fs.readFileSync('./key/7187579_huyi.icefery.xyz.key'),
     cert:fs.readFileSync('./key/7187579_huyi.icefery.xyz.pem')
}


const varifyToken = (token)=>{//验证token是否合法的方法
     let result = null;
     const secret = "kjafhkjsal";
         let {data,ctime,expiresIn} = jwt.verify(token,secret);
         let nowTime = (new Date()).getTime();
         if(nowTime-ctime<expiresIn){
             result = data;        
         }
     //console.log(result)
     return result;
 }

const tokenMiddlWare = (req,res,next)=>{
     let {token} = req.headers
     if(req._parsedUrl.pathname == '/api/session/login'
     ||req._parsedUrl.pathname == '/api/session/register'
     ||req._parsedUrl.pathname == '/api/session/update'
     ||req._parsedUrl.pathname == '/api/session/delete'
     )next()
     else if(token!=''&&token!='undefined'){
          let tokenState = varifyToken(token)
          console.log(token,'token',tokenState,'tokenState')
          next()
     }
     else res.json({
          code:400,
          message:'token不合法,请求拒绝',
     })
   }


const app = express()
app.use("/img",express.static("/img"))
app.use(cors())
app.use(express.json())
app.use(express.urlencoded({extended:true}))

app.use('/api/sort',tokenMiddlWare,sort)
app.use('/api/comment',tokenMiddlWare,comment)
app.use('/api/session',tokenMiddlWare,Session)
app.use('/api/blog',tokenMiddlWare,blog)
app.use('/api/banner',banner)

app.use('/w/api/sort',sort)
app.use('/w/api/comment',comment)
app.use('/w/api/session',Session)
app.use('/w/api/blog',blog)
app.use('/w/api/banner',banner)
app.use('/w/api/comment',comment)

app.use('/api/img',img)
app.use('/w/api/user_handle',user_handle)

app.get('/img/*',function (req, res) {
     console.log(req.url)
     res.sendFile( path.join(__dirname, req.url+'.png') )
})

const httpsServer = https.createServer(options,app);



httpsServer.listen(3001,() => {
     console.log('lis in 3001')
});
/* app.listen(3001,() => {
     console.log('lis in 3001')
}); */